/**
 * Copyright (c) 2012 Nokia Corporation. 
 */

package com.nokia.example.tictactoe.ui;

import java.util.Timer;
import java.util.TimerTask;

/**
 * A custom progress bar.
 */
public class TimedProgressBar extends ProgressBar {
	// Constants
	public static final int INTERVAL = 1000; // 1 second
	
	// Members
	private Listener _listener = null;
	private Timer _timer = null;
	private int _timeout = 0; // Milliseconds

	/**
	 * Constructor.
	 * @param width The maximum width of the progress bar.
	 */
	public TimedProgressBar(Listener listener, int width) {
		super(width);
		_listener = listener;
	}
	
	/**
	 * Starts the progress bar.
	 * @param timeout The duration in milliseconds.
	 */
	public void start(final int timeout) {
		if (timeout <= 0) {
			return;
		}

		cancel();
		_timeout = timeout;
		setValue(0);
		_timer = new Timer();
		_timer.scheduleAtFixedRate(new ProgressBarTimerTask(), INTERVAL, INTERVAL);
		repaint();
	}
	
	/**
	 * Cancels the timer.
	 */
	public void cancel() {
		if (_timer != null) {
			_timer.cancel();
			_timer = null;
		}
	}
	
	/**
	 * Interface for listener.
	 */
	public interface Listener {
		void onTimeout();
	}
	
	/**
	 * Timer task for increasing the progress bar value and notifying the
	 * listener after timeout. 
	 */
	private class ProgressBarTimerTask extends TimerTask {
		private int count = 0;

		public void run() {
			count++;
			
			if (count * INTERVAL >= _timeout) {
				// Timeout!
				if (_listener != null) {
					_listener.onTimeout();
				}
				
				_timer.cancel();
				_timer = null;
			}
			else {
				setValue(_value + MAX_VALUE / (_timeout / INTERVAL));
			}
			
			repaint();
		}
	}
}
